<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="授权列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="类型" :up-table="true" name="type" :options="flag"
                                     :value.sync="tpeVal"></form-select>
                        <form-select title="商户号" :up-table="true" name="mchtId" id='mchtId1' :options="mchtList"
                                     v-show="this.tpeVal=='0'" :value.sync="mchtIdValue"></form-select>
                        <form-select title="代理商户号" :sreach="true" :up-table="true" name="mchtId2" id='mchtId2'
                                     :options="mchtList" v-show="this.tpeVal=='1'" :value.sync="mcht_Val"></form-select>
                        <form-select title="电子券名称" :up-table="true" name="couponId" id='couponId' :options="coupList"
                                     v-show="this.tpeVal=='0'" :value.sync="copIdVal"></form-select>
                        <span class="pull-right">
                            <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                            <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                            <button type="button" class="btn btn-primary add pull-right"
                                    v-show="this.tpeVal=='0'">授权</button>
                        </span>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="authorize-body modal-body">
                    <table-modal :item="item" :columns-set="columnsSet" :columns-num="1"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <modal-container title="新增" v-el:add-modal v-ref:modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:add-mform>
                <div class="add-body modal-body">
                    <table-modal :item="item" :columns-set="columnsAddSet" :columns-num="1"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }
</style>
<style>
    #mchtId1 {
        display: inline-block;
    }

    #mchtId2 {
        display: inline-block;
    }

    #couponId {
        display: inline-block;
    }
</style>
<script>
    //解决datatables弹窗警告
    $.fn.dataTable.ext.errMode = 'none';
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'

    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js";
    import {dateTransform} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            rep: '',
            over: '',
            copId: '',
            mchtIdVal: '',
            tpeVal: '',
            copIdVal: '',
            mchtIdValue: '',
            mcht_Val: '',
            mchtList: [],
            coupList: [],
            item: {},
            columnsSet: [],
            columnsAddSet: [{
                title: "商户号",
                data: "mchtId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "电子券号",
                data: "couponId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "电子券名称",
                data: "couponName",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "代理商户名称",
                data: "grantMchtName",
                className: "operate"
            }, {
                title: "电子券数量",
                data: "couponNum",
                edit: true,
                className: "operate",
            }, {
                title: "有效结束日期",
                data: "validatyEnd",
                edit: true,
                readonly: true,
                className: "operate",
                render: function (data) {
                    return dateTransform(data)
                }
            }],
            flag: [
                {key: '授权', value: '0'},
                {key: '被授权', value: '1'}
            ]
        }),
        watch: {
            async mchtIdValue (v) {
                this.mchtIdVal = v;
                if (v != '') {
                    this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/coupon/couponAndRuleList",
                        data: {mchtId: v},
                        method: "POST"
                    }).then(response => {
                        let list = response.content.list;
                        if (list != '' && list != null && list != []) {
                            if (list.length > 1) {
                                list.unshift({key: '所有电子券', value: ''});
                                this.$set("coupList", list);
                            } else {
                                this.$set("coupList", list);
                            }
                        } else {
                            this.coupList = [];
                        }
                    }, error => {
                    });
                } else {
                    this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/coupon/couponAndRuleList",
                        data: {mchtId: "0"},
                        method: "POST"
                    }).then(response => {
                        let list = response.content.list;
                        if (list != '' && list != null && list != []) {
                            if (list.length > 1) {
                                list.unshift({key: '所有电子券', value: ''});
                                this.$set("coupList", list);
                            } else {
                                this.$set("coupList", list);
                            }
                        } else {
                            this.coupList = [];
                        }
                    }, error => {
                    });
                }
            },
            copIdVal (v) {
                this.copId = v;
                console.log(this.copId)
            },
            tpeVal (v) {
                console.log(v)
                if (v = '0') {
                    this.getSelect1();
                } else {
                    this.getSelect2();
                    self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/grant/query/" + JSON.parse(localStorage.getItem("id_token")).mchtId,
                        data: {'type': 1, 'mchtId': ''},
                        method: "POST"
                    })
                }
            }
        },
        methods: {
            //还原弹出框位置
            resetBindDrag () {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
                this.tpeVal = '0';
            },
            getSelect1 () {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: '/api/v2' + projectName_Url + '/plat/grant/queryMcht/' + mchtId,
                    data: {type: '0'},
                    method: "POST"
                }).then(response => {
                    let list = response.content.list;
                    if (list != '' && list != null && list != []) {
                        if (list.length > 1) {
                            list.unshift({key: '所有商户', value: ''});
                            self.$set("mchtList", list);
                            self.mchtIdValue = list[0].value;
                        } else {
                            self.$set("mchtList", list);
                            self.mchtIdValue = list[0].value;
                        }
                    }
                }, error => {
                });
            },
            getSelect2 () {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: '/api/v2' + projectName_Url + '/plat/grant/queryMcht/' + mchtId,
                    data: {type: '1'},
                    method: "POST"
                }).then(response => {
                    let list = response.content.list;
                    if (list != '' && list != null && list != []) {
                        if (list.length > 1) {
                            list.unshift({value: "", key: "所有商户"});
//                            list.unshift({key:'所有商户',value:''});
                            self.$set("mchtList", list);
                        } else {
                            self.$set("mchtList", list);
                        }
                    }
                }, error => {
                });
            },
            getCoupon () {
                let self = this;
                self.$post({
                    url: '/api/v2' + projectName_Url + '/plat/coupon/couponAndRuleList',
                    data: {mchtId: '0'},
                    method: "POST"
                }).then(response => {
                    let list = response.content.list;
                    if (list != '' && list != null && list != []) {
                        if (list.length > 1) {
                            list.unshift({key: '所有电子券', value: ''});
                            self.$set("coupList", list);
                        } else {
                            self.$set("coupList", list);
                        }
                    } else {
                        this.coupList = [];
                    }
                }, error => {
                });
            }
        },
        created () {
            //datatable所用数组
            columnsSet = [{
                title: "商户号",
                data: "grantMcht",
                edit: true,
                readonly: true,
                visible: false,
                className: "operate"
            }, {
                title: "商户名称",
                data: "grantMchtName",
                edit: true,
                readonly: true,
                visible: false,
                className: "operate"
            }, {
                title: "代理商户号",
                data: "mchtId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "代理商户名称",
                data: "mchtName",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "电子券号",
                data: "couponId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "电子券名称",
                data: "couponName",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "电子券数量",
                data: "couponNum",
                edit: true,
                className: "operate",
            }, {
                title: "状态",
                data: "state",
                className: "operate",
                render: function (data) {
                    var value;
                    if (data == "0") {
                        value = '待确认'
                    } else if (data == "1") {
                        value = '已确认'
                    } else {
                        value = "不接受"
                    }
                    return value;
                }
            }, {
                title: "有效结束日期",
                data: "validatyEnd",
                edit: true,
                readonly: true,
                className: "operate",
                render: function (data) {
                    return dateTransform(data)
                }
            }, {
                title: "类型",
                data: "type",
                visible: false,
                className: "operate"
            },
                {
                    title: "相关操作",
                    className: "operate",
                    width: "160px",
                    render: function (value, type, row) {
                        //  已拒绝 重新授权和删除
                        if (row.type == '0' && row.state == '2') {
                            return `
                        <button type="button" class="btn btn-primary btn-sm edit">重新授权</button>
                        <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                      `
                        } else if (row.type == '0') {
                            return `
                        <button type="button" class="btn btn-primary btn-sm edit">编辑</button>
                        <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                       `
                        } else {
                            return `

                        `
                        }
                    }
                }];
        },
        ready: async function () {
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            self.getCoupon();
            $('#mchtId2').css('display', 'none');
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
//                    return;
                    //发送请求
                    //被授权
                    if (_data.type == '1') {
                        _data.mchtId = _data.mchtId2;
                        _data.couponId = '';
                    } else {
                        if (JSON.parse(localStorage.getItem("id_token")).mchtId == '10000000') {
                            _data.mchtId = _data.mchtId;
                        } else {
                            _data.mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId;
                        }
                    }
                    var id = JSON.parse(localStorage.getItem("id_token")).mchtId;
                    var result = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/grant/query/" + id,
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.list || []
                    })
                    //即将过期的优惠券 有效日期显示红色
                    if (result.content.list != '' && result.content.list != null) {
                        for (var i in result.content.list) {
                            if (result.content.list[i].expireTime == 3) {
                                var trs = $('tbody tr td:nth-child(7)');
                                $(trs[i]).css('color', 'red');

                            }
                        }
                    }
                }
            });

            $(self.$el).on("click", ".edit", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                 //请求可授权数量
                   self.$post({
                      url: "/api/v2" + projectName_Url + "/plat/grant/accreditNum",
                      data: {'mchtId': self.item.grantMcht, 'couponId': self.item.couponId},
                      method: "POST"
                   }).then(response => {
                      self.over = response.content.surplusnum;       
                   }, error => {
                 });
                //动态生成
                setTimeout(() => {
                    var box = $("<p>授权数量:<span style='color:red'>" + self.item.couponNum + "</span>张</p><p>已发放数量:<span style='color:red'>" + self.item.issuedNum + "</span>张</p><p>已使用数量:<span style='color:red'>" + self.item.useNum + "</span>张</p><p>剩余数量:<span style='color:red'>" + self.over + "</span>张</p>");
                    $("p").remove('.authorize-body tbody tr:nth-child(7) td:nth-child(2) p');
                    $(".authorize-body tbody tr:nth-child(7) td:nth-child(2)").append(box);
                    console.log($(".authorize-body tbody tr:nth-child(7) td:nth-child(2)"));
                }, 350)
                //修改框里转化时间显示格式
                self.item.tmpTime = dataArray.validatyEnd;
                self.item.validatyEnd = dateTransform(dataArray.validatyEnd);
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler () {
                        var form = self.$els.mform;
                        var _data = serialize(form, {hash: true, disabled: true, empty: true});
                        //状态为待确认 请求当前接口
                        if (dataArray.state == '0' || dataArray.state == '1') {
                            _data.state = self.item.state
                            _data.validatyEnd = self.item.tmpTime
                            var result = await self.$post({
                                url: "/api/v2" + projectName_Url + "/plat/grant/update",
                                data: _data,
                                method: "POST"
                            });
                            Midway.alert({title: "操作提示", content: result.errorInfo})
                        } else if (dataArray.state == '2') {
//                            _data.couponNum  = self.item.couponNum.toString().split(',');
//                            _data.grantMcht  =  self.item.grantMcht.toString().split(',');
                            _data.validatyEnd = self.item.tmpTime
                            var result = await self.$post({
                                url: "/api/v2" + projectName_Url + "/plat/grant/againAuthorize",
                                data: _data,
                                method: "POST"
                            });
                            Midway.alert({title: "操作提示", content: result.errorInfo})
                        }
                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        couponNum: {
                            required: true,
                        }
                    }
                });
                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest('tr').get(0);
                var grantMchtName = dataTable.row(Row).data().grantMchtName;
                var couponId = dataTable.row(Row).data().couponId;
                var grantMcht = dataTable.row(Row).data().grantMcht;
                var mchtId = dataTable.row(Row).data().mchtId;
                var validatyEnd = dataTable.row(Row).data().validatyEnd;
                await Midway.confirm({
                    title: "删除授权",
                    content: "是否要删除授权名称:" + grantMchtName + "?"
                })
                var _data = {couponId: couponId, grantMcht: grantMcht, mchtId: mchtId, validatyEnd: validatyEnd}
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/grant/delete",
                    data: _data,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            });
            $(self.$el).on("click", ".add", function () {
                // var Row = $(this).closest('tr').get(0);
                // const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                // self.item = dataArray;
                if (self.mchtIdVal == '' || self.copId == '') {
                    Midway.alert({title: "操作提示", content: '请选择商户和对应的电子券'});
                    return false;
                }
//
                dateTime()
                //判断是否能新增
                self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/grant/check",
                    data: {'mchtId': self.mchtIdVal, 'couponId': self.copId},
                    method: "POST"
                }).then(response => {
                    if (response.respCode != '00') {
                        return false;
                    } else {
                        //新增弹框的详情
                        var obj;
                        self.$post({
                            url: "/api/v2" + projectName_Url + "/plat/coupon/" + self.mchtIdVal + '/' + self.copId,
                            method: "GET"
                        }).then(response => {
                            let list = response.content.coupon;
                            obj = {
                                'mchtId': list.mchtId,
                                'mchtName': response.content.mchtName,
                                'couponId': list.couponId,
                                'couponName': list.name,
                                'validatyEnd': list.validatyEnd
                            }
                            self.item = obj;
                            //新增框里转化时间显示格式
                            self.item.tmpTime = list.validatyEnd;
                            self.item.validatyEnd = dateTransform(list.validatyEnd);
                            //新增弹框代理商列表
                            self.$post({
                                url: "/api/v2" + projectName_Url + "/plat/grant/grantMchtList",
                                data: {'mchtId': list.mchtId, 'couponId': list.couponId},
                                method: "POST"
                            }).then(response => {
                                let list = response.content.list;
                                let _array = [];
                                if (list != null && list != '' && list != []) {
                                    for (let i = 0; i < list.length; i++) {
                                        _array.push({value: list[i].value, key: list[i].key});
                                    }
                                }
                                self.$set("columnsAddSet[4].options", _array)
                            }, error => {
                            });
                            //请求可授权数量
                            self.$post({
                                url: "/api/v2" + projectName_Url + "/plat/grant/accreditNum",
                                data: {'mchtId': self.item.mchtId, 'couponId': self.item.couponId},
                                method: "POST"
                            }).then(response => {
                                self.over = response.content.surplusnum;
                                //动态生成
                                var box = $("<p>剩余数量:<span style='color:red'>" + response.content.surplusnum + "</span>张</p>");
                                setTimeout(() => {
                                    $("p").remove('.add-body tbody tr:nth-child(6) td:nth-child(2) p');
                                    $(".add-body tbody tr:nth-child(6) td:nth-child(2)").append(box);
                                }, 500)
                            }, error => {
                            });

                        }, error => {
                        });
                        //新增框验证、保存、提交
                        $(self.$els.addMform).validate(self.item.valdate = {
                            async submitHandler () {
                                var form = self.$els.addMform;
                                var _data = serialize(form, {hash: true, disabled: true, empty: true});
                                //代理商户数据处理
                                var grantMchtName = _data.grantMchtName;
                                var _mchtsArr = '';
                                _mchtsArr = grantMchtName.toString().split(',');
                                _data.grantMcht = _mchtsArr;

                                //优惠券张数处理
                                var coupNum = _data.couponNum;
                                var _numArr = '';
                                _numArr = coupNum.toString().split(',');
                                _data.couponNum = _numArr;

                                if (self.over == '0') {
                                    Midway.alert({title: "操作提示", content: '可授权的数量为0'});
                                    return false;
                                }
                                _data.validatyEnd = self.item.tmpTime;
                                var result = await self.$post({
                                    url: "/api/v2" + projectName_Url + "/plat/grant/add",
                                    data: _data,
                                    method: "POST"
                                });
                                Midway.alert({title: "操作提示", content: result.errorInfo});
                                dataTable.ajax.reload(null, false);
                                $(self.$els.addModal).modal('hide');
                                self.resetBindDrag()
                            },
                            rules: {
                                grantMchtName: {
                                    required: true
                                },
                                couponNum: {
                                    required: true,
                                    int: true,
                                    min: 1
                                }
                            }
                        });
                        $(self.$els.addModal).modal('show');
                    }
                }, error => {
                });

            });
        },
        beforeDestroy () {
            $(this.$el).off("click")
        }
    }
</script>
